﻿using AutoMapper;
using AutoMapper.Internal.Mappers;
using GuanYijia.Application.IntPut;
using GuanYijia.Application.OutPut;
using GuanYijia.DoMain;
using GuanYijia.DoMain.RBAC;
using GuanYijia.Repository;
using GuanYiJia.WebApi;
using IdentityModel;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using Org.BouncyCastle.Crypto.Generators;
using Panda.DynamicWebApi;
using Panda.DynamicWebApi.Attributes;
using System.Diagnostics;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;

namespace GuanYijia.Application.UserBusinessManagement
{
    [DynamicWebApi]
    [ApiExplorerSettings(GroupName = "v1")]
    [Authorize]
    public class UserBusinessDataService : IDynamicWebApi
    {
        private readonly IBaseRepository<User> _userIBaseRepository;
        private readonly IBaseRepository<CustomLog> 
_customLogIBaseRepository;
        private readonly IMapper _mapper;
      
        private readonly IConfiguration configuration;
        private readonly IHttpContextAccessor httpContextAccessor;
        private readonly IBaseRepository<Permissions> _permissionsIBaseRepository;
        private readonly IBaseRepository<RolePermissions> _rolePermissionsIBaseRepository;
        private readonly IBaseRepository<UserBusiness> _userBusinessIBaseRepository;
        private readonly IBaseRepository<Role> _roleIBaseRepository;

        //构造函数注入: 通过构造函数将依赖项传递给类，确保对象在创建时获得所需的依赖。

        //属性注入: 通过公共属性设置依赖项，适用于可选的或可修改的依赖项。

        //方法注入: 依赖项作为方法参数传入，适合在方法调用时动态提供依赖。
        public UserBusinessDataService(IBaseRepository<User> userIBaseRepository, IMapper mapper, IConfiguration configuration, IHttpContextAccessor httpContextAccessor, IBaseRepository<CustomLog> customLogIBaseRepository, IBaseRepository<Permissions> permissionsIBaseRepository, IBaseRepository<RolePermissions> rolePermissionsIBaseRepository, IBaseRepository<UserBusiness> userBusinessIBaseRepository, IBaseRepository<Role> roleIBaseRepository)
        {
            _userIBaseRepository = userIBaseRepository;
            _mapper = mapper;
            this.configuration = configuration;
            this.httpContextAccessor = httpContextAccessor;
            _customLogIBaseRepository = customLogIBaseRepository;
            _permissionsIBaseRepository = permissionsIBaseRepository;
            _rolePermissionsIBaseRepository = rolePermissionsIBaseRepository;
            _userBusinessIBaseRepository = userBusinessIBaseRepository;
            _roleIBaseRepository = roleIBaseRepository;
        
        }
        [AllowAnonymous]
        public object GetNew()
        {
            using (RSA rsa = RSA.Create(2048)) // 2048位密钥
            {
                string publicKey = Convert.ToBase64String(rsa.ExportSubjectPublicKeyInfo());
                string privateKey = Convert.ToBase64String(rsa.ExportPkcs8PrivateKey());
                Console.WriteLine("公钥:");
                Console.WriteLine(publicKey);
                Console.WriteLine("私钥:");
                Console.WriteLine(privateKey);
                return new { publicKey, privateKey };
            }
        }

        //[AllowAnonymous]
        //public RSAPWD GetJiaJieMi(string pwd)
        //{
        //    RSAPWD PWD = new RSAPWD();
        //    // 请在这里填入你的公钥和私钥
        //    string publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5CArC+lfbxghN7osj8JEPR4dRfQx5+YJcxB7tB8z6DxFf74NLSUtBQOlONe0ayRcArMbhh2k0KGwm2wQMSe+JkGruq5jDK7MLDVtUOmY4nZBDw9tUavctHJPacq+DMzttkNSqddWDu7m2a7OfJcmO0bAd4qEeKOGETig1c3fY02T2EWfSYh9NYGlGt1tsrfjXzZ0IT0od4IpyzO0ycmUSX2P0KgtLadSVGiI8p7OZvO/IZt/efktE1f9Cs6h0WyDOk6mmaodp/GHO7R/D8C24TqSD198LTJNFW3tbHR7ZzijcVw38LBnfbwXeI506B4L+2bX7cuRFayBW3FKSrkGFQIDAQAB"; // Base64 编码的公钥
        //    string privateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDkICsL6V9vGCE3uiyPwkQ9Hh1F9DHn5glzEHu0HzPoPEV/vg0tJS0FA6U417RrJFwCsxuGHaTQobCbbBAxJ74mQau6rmMMrswsNW1Q6ZjidkEPD21Rq9y0ck9pyr4MzO22Q1Kp11YO7ubZrs58lyY7RsB3ioR4o4YROKDVzd9jTZPYRZ9JiH01gaUa3W2yt+NfNnQhPSh3ginLM7TJyZRJfY/QqC0tp1JUaIjyns5m878hm395+S0TV/0KzqHRbIM6TqaZqh2n8Yc7tH8PwLbhOpIPX3wtMk0Vbe1sdHtnOKNxXDfwsGd9vBd4jnToHgv7Ztfty5EVrIFbcUpKuQYVAgMBAAECggEAJHAO8CQinjgYdjJCk+PPyoNY4aeToRrZP4vOdoLVY67c2v6cVC2v9zER3vZ1VvfDypqZNt7dSIXLE8g6/d7/PFUY/QSFxazV5+nQwC/Pv7xrv+AS8gylgB0SGi/ME3dYMNioB4DhuhjmvrZxPO1XqfgvHej+J9bWv0FwTzZHDDE2yrBh3ROrHUbTneVGUMmbDlyibIwIkP0visDzl37TOoWRo4InXrnIf1JI5q4HbyWObgIhQr4apAOzgjYk3R3X13TYv8vRsJAiLPau55SqkYn44oe3KyPc+vWOgmlmVY8oO0VuGROJSsetQSfSfB2JhKBxbg/2lFlksTR+1I/0sQKBgQD1S/kLVDW8YLcgyoShCQ/Bu+U+NHzFPFEjzOCpKFTvqMLUbOLNgMfRjZlWEMtmn4Bqrz9vqFqbd5S846hilpkt9o80R+hTYF2odB3nK1ATxhDhQaHbHBb/07NgSsfJjCYbKgTe8OLoLe5s1rDrqg/uY0huazHCp4GA/HqRrc3K4wKBgQDuFGO/jRr9dSvs9zWUEjr3SCed+nv7nN9tS35rx1n4CXoqZCrXrmj2O9WNPvp7gqhPkPbVfuCpnu79GR7Vy7s+1OYUyS8FWs3PyTrv+XtxW89Xet7x5U5cpMKidR5xg65Ronh5zlzYqhG/7+akcDy8mYnFNLNSe3jwp+jtaTNkpwKBgBSIjYpjPDROrEW0bjHEvmrrPZ9daWxhRjGG/u9qDuIY8GYzzzCArTlfbwyDT2OBypAjp13DbAJDmlHNhNTr4lq0nvwzYMFJ+c0WG0K0n3loRRV2FwRub4ZuxD81Q1AdyTrQ46N96qCg56p4tkqj67161h9YHcw7lV2kxOXY9LcdAoGASYI8JimgOr/R1zGg9l4GnNFHgiyT2WVfSvSzTP3ZVo8+jBYvcDamq9hfoGPgnQADjcWZoOOy5ExxR+5YqfRklQrRG3veq82UnGJqcyvZpG+PflguvAtr/YjVm6mDw9K/oO8EOb+wxSkFn/ingwAwkJ7rfds+vunmto9xiNQhjSMCgYEA04OOznICKlIGQ/qpGf3toj1+KNQZ9KryeXrPDTev5vHHskNhpk3nCjTQFl5ZSTMsiqIXCNTlV/i7qhOEm2ikyWUdwXrFtIUc7SQI8cbAsNWHbPHevALT/O+kUXvWJT9VOrLHOv1xtSM2ul18CHArEP7C6Voroeqy2KEGxTDBg9A="; // Base64 编码的私钥

        //    RSAHelper rsaHelper = new RSAHelper(publicKey, privateKey);
        //    string password = pwd; // 要加密的密码
        //    try
        //    {
        //        string encryptedPassword = rsaHelper.Encrypt(password);
        //        Console.WriteLine("加密后的密码: " + encryptedPassword);
        //        PWD.EncryptedPassword = encryptedPassword;

        //        string decryptedPassword = rsaHelper.Decrypt(encryptedPassword);
        //        Console.WriteLine("解密后的密码: " + decryptedPassword);
        //        PWD.DecryptedPassword = decryptedPassword;

        //        return PWD;
        //    }
        //    catch (Exception ex)
        //    {
        //        Console.WriteLine($"处理失败: {ex.Message}");
        //        return null; // 或返回适当的错误信息
        //    }
        //}
        /// <summary>
        /// 获取盐的方法
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentException"></exception>
        [AllowAnonymous]
        public  byte[] GenerateSalt(int length = 32)
        {
            if (length <= 0)
            {
                throw new ArgumentException("盐的长度必须大于0", nameof(length));
            }

            byte[] salt = new byte[length];
            using (var rng = new RNGCryptoServiceProvider())
            {
                rng.GetBytes(salt); // 填充盐数组
            }

            return salt; // 返回生成的盐
        }
       /// <summary>
       /// 获取哈希加盐后的密码
       /// </summary>
       /// <param name="password"></param>
       /// <param name="salt"></param>
       /// <returns></returns>
       /// <exception cref="ArgumentException"></exception>
        [AllowAnonymous]
        [HttpGet]
        public string HashPassword(string password, byte[] salt)
        {
            // 检查输入的参数是否有效
            if (string.IsNullOrEmpty(password))
            {
                throw new ArgumentException("密码不能为空", nameof(password));
            }

            if (salt == null || salt.Length != 32) // 确保盐的长度正确
            {
                throw new ArgumentException("盐必须是32字节长", nameof(salt));
            }

            // 使用 Rfc2898DeriveBytes 进行哈希
            using (var pbkdf2 = new Rfc2898DeriveBytes(password, salt, 10000))
            {
                byte[] hash = pbkdf2.GetBytes(32); // 生成32字节的哈希

                // 创建一个字节数组来存储盐和哈希结果
                byte[] hashBytes = new byte[64]; // 盐(32字节) + 哈希结果(32字节)
                Buffer.BlockCopy(salt, 0, hashBytes, 0, 32); // 将盐复制到前32字节
                Buffer.BlockCopy(hash, 0, hashBytes, 32, 32); // 将哈希结果复制到后32字节

                // 返回盐和哈希的组合结果，使用 Base64 编码
                return Convert.ToBase64String(hashBytes);
            }    
        }
        /// <summary>
        /// 判断与输入的密码是否相同
        /// </summary>
        /// <param name="inputPassword"></param>
        /// <param name="storedHash"></param>
        /// <returns></returns>
        public bool VerifyPassword(string inputPassword, string storedHash)
        {
            byte[] hashBytes = Convert.FromBase64String(storedHash);
            byte[] salt = new byte[32]; // 从存储的哈希中提取盐
            Buffer.BlockCopy(hashBytes, 0, salt, 0, 32); // 盐在前32字节

            // 使用相同的盐对输入密码进行哈希
            using (var pbkdf2 = new Rfc2898DeriveBytes(inputPassword, salt, 10000))
            {
                byte[] hash = pbkdf2.GetBytes(32); // 计算哈希
                for (int i = 0; i < 32; i++)
                {
                    if (hashBytes[i + 32] != hash[i]) return false; // 比较哈希
                }
            }
            return true; // 如果哈希匹配，返回true
        }
        /// <summary>
        /// 登录功能
        /// </summary>
        /// <param name="intPut">登录的参数类</param>
        /// <returns>返回对象</returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<UserLoginOutPut<UserOutput>> Login(UserLoginIntPut intPut)
        {
            UserLoginOutPut<UserOutput> output = new();
            var model = await _userIBaseRepository.GetAllAsync(d => d.login_name == intPut.name);

            if (model.Count < 1)
            {
                output.Code = -1; // 账户不存在
                output.Message = "账户不存在";
            }
            else
            {
                var FirstModel = model.First();
                string storedHash = FirstModel.password; // 假设 password 存储的是盐+哈希
                if (!VerifyPassword(intPut.pwd, storedHash))
                {
                    output.Code = -2; // 密码错误
                    output.Message = "密码错误";
                }
                else
                {
                    var result = await _userBusinessIBaseRepository.GetAsync(d => d.userId == FirstModel.userId);
                    output.Code = 1; // 登录成功
                    output.Message = "登录成功";
                    var entity = _mapper.Map<UserOutput>(FirstModel);
                    output.User = entity;

                    // 调用生成 Token 方法
                    var authInfo = MakeJwtAction(FirstModel);
                    output.authInfo = authInfo;
                    output.roleId = result.roleid;
                }
            }
            return output;
        }
        /// <summary>
        /// 获取token
        /// </summary>
        /// <param name="admin"></param>
        /// <returns></returns>
        public string MakeJwtAction(User admin)
        {
            //写Session或Cookies换成JWT


            IList<Claim> claims = new List<Claim> {
                        new Claim(JwtClaimTypes.Id,admin.userId.ToString()),
                        new Claim(JwtClaimTypes.Name,admin.login_name),
                    };
            var claimsnew = new List<Claim>
            {
                new Claim("custom_id", admin.userId.ToString()),
                new Claim(ClaimTypes.Name, admin.login_name)
            };

            var identity = new ClaimsIdentity(claimsnew, "login");
            var claimsPrincipal = new ClaimsPrincipal(identity);
            httpContextAccessor.HttpContext.User = claimsPrincipal; // 确保 User 被正确设置

            //JWT密钥
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JwtConfig:Bearer:SecurityKey"]));

            //算法
            var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            //过期时间
            DateTime expires = DateTime.UtcNow.AddHours(30);


            //Payload负载
            var token = new JwtSecurityToken(
                issuer: configuration["JwtConfig:Bearer:Issuer"],
                audience: configuration["JwtConfig:Bearer:Audience"],
                claims: claims,
                notBefore: DateTime.UtcNow,
                expires: expires,
                signingCredentials: cred
                );

            var handler = new JwtSecurityTokenHandler();

            //生成令牌
            string jwt = handler.WriteToken(token);
            return jwt;
        }
        /// <summary>
        /// 获取全局日志列表
        /// </summary>
        /// <param name="logListInt"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        [SkipCustomFilterAttribute]
        public async Task<LogListOutPut> GetLogList(LogListIntPut logListInt)
        {
            LogListOutPut output = new LogListOutPut();
            var list = await _customLogIBaseRepository.GetAllAsync();
            if (logListInt.operation != null)
            {
                list = list.Where(d => d.operation.Contains(logListInt.operation)).ToList();
            }
            if (logListInt.content != null)
            {
                list = list.Where(d => d.content.Contains(logListInt.content)).ToList();
            }
            if (logListInt.loginname != null)
            {
                list = list.Where(d => d != null && d.loginname != null && d.loginname.Contains(logListInt.loginname)).ToList();
            }
            if (logListInt.create_timestart != null)
            {
                list = list.Where(d => DateTime.Parse(d.create_time) < logListInt.create_timestart).ToList();
            }
            if (logListInt.create_timeend != null)
            {
                list = list.Where(d => DateTime.Parse(d.create_time) < logListInt.create_timeend).ToList();
            }
            
            output.pageTotal = list.Count();
            output.pageCount = (int)Math.Ceiling(list.Count() * 1.0 / logListInt.pageSize);
            list= list.OrderBy(D=>D.CustomLogId).Skip((logListInt.pageIndex-1)*logListInt.pageSize).Take(logListInt.pageSize).ToList();
            output.Data = list;
            return output;
        }
        [AllowAnonymous]
        public async Task<List<UserMenuOutput>> GetMenus(int roleId, int? parentid = 0)
        {
            var result = from a in await _rolePermissionsIBaseRepository.GetAllAsync()
                         join b in await _permissionsIBaseRepository.GetAllAsync() on a.PermissionsId equals b.PermissionsId
                         where a.roleid == roleId
                         select new
                         {
                             a.RolePermissionsId,
                             a.roleid,
                             a.PermissionsId,
                             b.permission_name,
                             b.permission_url,
                             b.ParentId,
                             b.permission_description,
                             b.IsMenu
                         };

            result = result.ToList();
            var List= result.Where(d=>d.ParentId== parentid);
            List<UserMenuOutput> userMenus = new();
            foreach (var item in List)
            {
                UserMenuOutput output=new UserMenuOutput();
                output.MenuId = item.PermissionsId;
                output.MenuName = item.permission_name;
                output.ParentId = item.ParentId;
                output.Url = item.permission_url;
                output.Children = await GetMenus(roleId,item.PermissionsId);
                userMenus.Add(output);
            }
            return userMenus;
        }
        /// <summary>
        ///   获取角色列表
        /// </summary>
        /// <param name="roleListinput"></param>
        /// <returns></returns>
        [HttpPost]
        [SkipCustomFilterAttribute]
        public async Task<RoleListOutPut> GetRoleList(RoleListIntPut roleListinput)
        {
            RoleListOutPut output = new RoleListOutPut();
            var list=await _roleIBaseRepository.GetAllAsync();
            if (!string.IsNullOrEmpty(roleListinput.rolename))
            {
                list = list.Where(d => d.name.Contains(roleListinput.rolename)).ToList();
            }
            if (!string.IsNullOrEmpty(roleListinput.desc))
            {
                list = list.Where(d => d.description.Contains(roleListinput.desc)).ToList();
            }
            output.pageTotal= list.Count();
            output.pageCount = (int)Math.Ceiling(list.Count() * 1.0 / roleListinput.pageSize);
            output.Data= list.OrderByDescending(d=>d.roleid).Skip((roleListinput.pageIndex-1)* roleListinput.pageSize).Take(roleListinput.pageSize).ToList();
            return output;
        }
        /// <summary>
        /// 添加角色
        /// </summary>
        /// <param name="addroleintput"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<int> AddRole(AddRoleIntPut addroleintput)
        {
           var entoty= _mapper.Map<Role>(addroleintput);
           return await _roleIBaseRepository.InsertAsync(entoty);
        }
        /// <summary>
        /// 添加分配角色
        /// </summary>
        /// <param name="parentid"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet]
        public async Task<List<Cascader>> AddRoleShowList(int parentid = 0)
        {
        

           var result = await _permissionsIBaseRepository.GetAllAsync();
            var List = result.Where(d => d.ParentId == parentid);
            List<Cascader> userMenus = new();
            foreach (var item in List)
            {
                Cascader output = new Cascader();
                output.Value = item.PermissionsId;
                output.Label = item.permission_name;
                output.Children = await AddRoleShowList(item.PermissionsId);
                userMenus.Add(output);
            }
            return userMenus;
        }
        /// <summary>
        /// 根据roleid获取权限
        /// </summary>
        /// <param name="roleid"></param>
        /// <param name="parentid"></param>
        /// <returns></returns>
        [AllowAnonymous]
        public async Task<List<Cascader>> GetRolePermisssionById(int roleid,int parentid=0)
        {
            List<Cascader> userMenus = new();
            
            var result = from a in await _permissionsIBaseRepository.GetAllAsync()
                         join b in await _rolePermissionsIBaseRepository.GetAllAsync() on a.PermissionsId equals b.PermissionsId
                         where b.roleid== roleid
                         select new
                         {
                             a.permission_name,
                             a.PermissionsId,
                             b.roleid,
                             a.ParentId
                         };
            var List = result.Where(d => d.ParentId == parentid);
          
            foreach (var item in List)
            {
                Cascader output = new Cascader();
                output.Value = item.PermissionsId;
                output.Label = item.permission_name;
                output.Children = await GetRolePermisssionById(roleid,item.PermissionsId);
                userMenus.Add(output);
            }
            return userMenus;    
        }   
        /// <summary>
        /// 添加角色权限
        /// </summary>
        /// <param name="addroleperssion"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<int> AddRolePerssion(AddRolePerssionIntPut addroleperssion)
        {
            int index = 0;

            var existingPermissions = await _rolePermissionsIBaseRepository
                .GetAllAsync(d => d.roleid == addroleperssion.roleId);

            var existingPermissionsSet = new HashSet<int?>(existingPermissions.Select(rp => rp.PermissionsId));
            var newPermissionsSet = new HashSet<int>(addroleperssion.data);

            // 新增权限
            foreach (var item in newPermissionsSet)
            {
                if (!existingPermissionsSet.Contains(item))
                {
                    RolePermissions rolePermissions = new RolePermissions
                    {
                        roleid = addroleperssion.roleId,
                        PermissionsId = item
                    };
                    index += await _rolePermissionsIBaseRepository.InsertAsync(rolePermissions);
                }
            }

            // 删除未选择的权限
            foreach (var existingItem in existingPermissionsSet)
            {
                if (!newPermissionsSet.Contains((int)existingItem))
                {
                    var permissionToDelete = existingPermissions.FirstOrDefault(rp => rp.PermissionsId == existingItem);
                    if (permissionToDelete != null)
                    {
                        index += await _rolePermissionsIBaseRepository.DeletedAsync(permissionToDelete);
                    }
                }
            }

            return index;
        }
        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="getuserintput"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        [SkipCustomFilterAttribute]
        public UserListOutPut GetUser(GetUserIntPut getuserintput)
        {
            UserListOutPut outPut = new UserListOutPut();

            // 获取 IQueryable 用户和用户业务，使用 AsNoTracking
            var userQuery = _userIBaseRepository.GetQueryable(tracking: false);
            var aa = userQuery.Count();
            var userBusinessQuery = _userBusinessIBaseRepository.GetQueryable(tracking: false);

            var bb = userBusinessQuery.Count(); var query = from a in userQuery
                        join b in userBusinessQuery on a.userId equals b.userId
                        select new
                        {
                            a.userId,
                            a.username,
                            a.login_name,
                            a.password,
                            a.leader_flag,
                            a.position,
                            a.department,
                            a.email,
                            a.phonenum,
                            a.ismanager,
                            a.isystem,
                            a.Status,
                            a.description,
                            a.remark,
                            a.tenant_id,
                            b.roleid
                        };

            // 添加筛选条件
            if (getuserintput.loginname!=null)
            {
                query = query.Where(d => d.login_name.Contains(getuserintput.loginname));
            }
            if (getuserintput.username!=null)
            {
                query = query.Where(d => d.username.Contains(getuserintput.username));
            }
            var results = query.ToList();
            // 计算总记录数
            outPut.pageTotal = results.Count();

            // 计算总页数
            outPut.pageCount = (int)Math.Ceiling(outPut.pageTotal * 1.0 / getuserintput.pageSize);

            // 进行分页
            outPut.Data =  query.OrderByDescending(d => d.userId)
                                      .Skip((getuserintput.pageIndex - 1) * getuserintput.pageSize)
                                      .Take(getuserintput.pageSize)
                                      .ToList();

            return outPut;
        }
        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="adduser"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public async Task<int> AddUser(AddUserIntPut adduser)
        {
            int idnex = 0;
           var list=await  _userIBaseRepository.GetAllAsync(d => d.login_name == adduser.login_name);
            if(list.Count > 0)
            {
                return -1;
            }
            else {
                User uu = new User();
                uu.username=adduser.username;
                uu.password=adduser.password;
                uu.login_name=adduser.login_name;
                uu.leader_flag= adduser.leader_flag;
                uu.position=adduser.position;
                uu.description=adduser.description;
                uu.department=adduser.department;
                uu.email=adduser.email;
                uu.phonenum=adduser.phonenum;
                uu.ismanager=adduser.ismanager;
                uu.isystem=adduser.isystem;
                uu.Status=adduser.Status;
                uu.remark=adduser.remark;
                uu.tenant_id=adduser.tenant_id;
                 await _userIBaseRepository.InsertAsync(uu);
                UserBusiness user = new UserBusiness();
                user.roleid = adduser.roleid;
                user.userId = uu.userId;
                user.delete_flag = false;
                idnex+=await _userBusinessIBaseRepository.InsertAsync(user);

                return idnex;
            }
          
        }
        /// <summary>
        /// 获取角色下拉框
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [SkipCustomFilterAttribute]
        public async Task<List<Role>> GetRole()
        {
           return await _roleIBaseRepository.GetAllAsync();
        }
        











    }
}